﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing.Imaging;
using System.Drawing;
using System.Net;
using System.IO;
using System.Text;
using uQR.Extensions;

namespace uQR.Web
{
    public class uQRHandler : IHttpHandler
    {
        public const string CHARTS_URL = "http://chart.apis.google.com/chart";

        public bool IsReusable { get { return false; } }

        public void ProcessRequest(HttpContext context)
        {
            // Cache any barcode for a month based on parameters
            TimeSpan freshness = new TimeSpan(31, 0, 0, 0);

            context.Response.Cache.SetExpires(DateTime.Now.Add(freshness));
            context.Response.Cache.SetMaxAge(freshness);
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetValidUntilExpires(true);
            context.Response.Cache.VaryByParams["*"] = true; 

            // Parse input
            var data = context.Request.QueryString["data"];

            var width = !string.IsNullOrEmpty(context.Request.QueryString["width"]) ?
                Convert.ToInt32(context.Request.QueryString["width"]) :
                200;

            var height = !string.IsNullOrEmpty(context.Request.QueryString["height"]) ?
                Convert.ToInt32(context.Request.QueryString["height"]) :
                width;

            var correction = !string.IsNullOrEmpty(context.Request.QueryString["correction"]) ?
                context.Request.QueryString["correction"].ToUpper() :
                "M";

            // Build form data
            var postData = string.Format("cht=qr&chl={0}&chs={1}x{2}&chld={3}",
                HttpUtility.UrlEncode(data),
                width,
                height,
                correction);

            var postDataBytes = new UTF8Encoding().GetBytes(postData);

            // Get chart
            var request =  (HttpWebRequest)WebRequest.Create(CHARTS_URL);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataBytes.Length;

            var stream = request.GetRequestStream();
            stream.Write(postDataBytes, 0, postDataBytes.Length);
            stream.Close();

            context.Response.ContentType = "image/png";
            request.GetResponse().GetResponseStream().CopyTo(context.Response.OutputStream);
        }
    }
}